package org.csu.myPetStore.web.servlet.Cart;

import org.csu.myPetStore.domain.Account;
import org.csu.myPetStore.domain.Cart;
import org.csu.myPetStore.domain.Item;
import org.csu.myPetStore.service.CartService;
import org.csu.myPetStore.service.LogcatService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

public class RemoveItemFromCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    private static final String LOGIN = "/WEB-INF/jsp/account/SignonForm.jsp";
    private String workingItemId;
    private Cart cart;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    //bug::remove之后,刷新界面，无法出席ERROR对应jsp

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        workingItemId = req.getParameter("workingItemId");
        CartService service = new CartService();
        LogcatService logcatService = new LogcatService();

        HttpSession session = req.getSession();
        cart = (Cart) session.getAttribute("cart");
        Account account = (Account) session.getAttribute("account");

        if(account == null)
            req.getRequestDispatcher(LOGIN).forward(req,resp);

        else {
            //移除session信息
            Item item = cart.removeItemById(workingItemId);
            //删除cart数据库信息
            service.deleteCartItemFromUserByItemId(workingItemId,account.getUsername());

            //添加日志信息
            java.util.Date date = new java.util.Date();
            Date datesql = new Date(date.getTime());
            logcatService.InsertLogCat(account.getUsername(),"Remove" + item.getProduct().getName() + "from cast at " + datesql.toString());


            if(item == null){
                session.setAttribute("message","Error,Attempted to remove null CartItem from Cart.");
                req.getRequestDispatcher(ERROR).forward(req,resp);
            }else{
                req.getRequestDispatcher(VIEW_CART).forward(req,resp);
            }
        }

    }

}
